/**
 * Created by gongxun on 16/11/20.
 */

var GameUserInfo = function(){
    var that = {};

    that.uid = null;

    that.user = null;

    that.deviceInfo = null;

    that.myClientIp = null;

    //音乐 和音效
    that.mMusicVolume = null;
    that.mEffectsVolume = null;

    //方言
    that.mLocalism = null;

    //自定义消息发送次数
    that.userCustomTextRate = null;

    //自定义表情发送次数
    that.userCostomFaceRate = null;

    //自定义消息的排序结构体
    that.userCustomTextRateStruct = null;

    //自定义消息的排序结构体
    that.userCostomFaceRateStruct = null;

    //kwx牌
    that.mGameKwxCardIndex = null;
    that.mGameKwxBgIndex = null;

    //本地保存的数据
    that.deviceInfoDesc = null;

    //定位的名称
    that.phoneLocationCHS = "未能获取地理位置";

    //经纬度 纬度
    that.latitude = null;

    //经纬度 经度
    that.longitude = null;

    //延迟（毫秒）
    that.gameDealytime = null;

    //地址的邮编
    that.admCode = "";

    //玩家自定义消息
    that.userCustomText = [
        "天空一声巨响，赌神闪亮登场",
        "大家好，都来了，看到你们高兴得很啊",
        "你是故意的吧？快点出牌，磨蹭什么呢",
        "小牌怡情，大牌成家立业",
        "不得了啊，你的牌打得太好了",
        "瞎闹什么，好好打你的牌，这把不行，下把来",
        "惊天动地清一色，移花接木杠上开",
        "找到组织，找到党，有个门子，绝不让",
        "每场必到，绝不迟到，差人就上，绝不谦让",
        "打了一冬的柴禾，一把火烧干了",
        "宁挨千刀和万剐，坚决不胡第一把",
        "小屁小屁走向胜利",
        "拜拜，我会想你们的"
    ];

    //设置用户uid
    that.setUserId = function(uid){
        that.uid = uid;

        mo.eventHelper.dispatch("UserIdChange");
    };

    that.setUser = function(user){
        that.user = user;
        if (user != null){
            //通知ui刷新界面
            that.uid = user.userid;
            mo.eventHelper.dispatch("updateUserInfo");

            //准备记录
            mo.loginHelper.saveTryRemark(user.Remark);
        }
    };

    //设置外部url回调
    that.setExternalOpen = function(url){
        var delayTime = 0.1;

        mo.sceneMainLayer.scheduleOnce(function(){
            // mo.showRoomMsgShow(url);
            // that.joinTableInfo = null;
            //check=MjMobile
            //type=0:加入房间(私人) 1:加入房间(公开) 2:播放录像 3:加群
            //param=参数
            //param2=额外的参数

            var param = mo.gameHelper.getUrlParam(url);
            if (param["check"] != undefined){
                that.joinTableInfo = param;

                //拉一次
                that.tryJoinTable();
                // mo.sceneMainLayer.scheduleOnce(function(){
                // }, 0.5);
            }
        }, delayTime);
    };

    //尝试处理外部信息
    that.tryJoinTable = function(){
        if (mo.gameHelper.testVersion != 0){

            if (that.joinTableInfo == null){
                cc.log("没有取道参数");
                return;
            }

            if (that.joinTableInfo["check"] != "MjMobile"){
                cc.log("参数有误");
                return;
            }

            var type = that.joinTableInfo["type"];
            if (type == "1"){
                var roomId = that.joinTableInfo["param"];
                mo.testHallLayer.setJoinTableId(roomId)
            }

            return;
        }


        cc.log("尝试处理外部信息");
        cc.log("当前的位置:" + mo.sceneHelper.currentLayerName);

        if (that.joinTableInfo == null){
            cc.log("没有取道参数");
            return;
        }

        if (that.joinTableInfo["check"] != "MjMobile"){
            cc.log("参数有误");
            return;
        }

        if (mo.sceneHelper.currentLayerName == "login"){
            cc.log("在大厅尝试打开");
            mo.loginHelper.tryLogin();
            return;
        }

        if (!mo.gameWebsocket.mIsConnect){
            cc.log("没有联网等待重连");
            return;
        }

        var type = that.joinTableInfo["type"];
        if (type == "0"){
            //不处理了
            //加入房间(私人)
            // var pwd = that.joinTableInfo["param"];
            // if (mo.sceneHelper.currentLayerName == "hall"){
            // if (parseInt(pwd) < 200000){
            //     //kwx
            //     mo.gameMsgManager.sendJoinFreeRequestkwxJoin(mo.gameUserInfo.uid, -2, pwd);
            // }else if (parseInt(pwd) < 300000){
            //     //nn
            //     mo.gameMsgManager.sendJoinFreeRequestnnJoin(mo.gameUserInfo.uid, -2, pwd);
            // }else if (parseInt(pwd) > 400000 && parseInt(pwd) < 500000){
            //     //ttz
            //     mo.gameMsgManager.sendJoinFreeRequestgsbdxJoin(mo.gameUserInfo.uid, -2, pwd);
            // }else if (parseInt(pwd) > 500000 && parseInt(pwd) < 600000){
            //     //psz
            //     mo.gameMsgManager.sendJoinFreeRequestpszJoin(mo.gameUserInfo.uid, -2, pwd);
            // }
            //     that.joinTableInfo = null;
            // }
        }else if (type == "1"){
            //加入房间(公开)
            var roomId = that.joinTableInfo["param"];
            if (mo.sceneHelper.currentLayerName == "hall"){
                var roomNum = parseInt(roomId);
                var gameName = mo.gameHelper.getGameNameForRoomId(roomNum);

                //加入房间等待界面
                mo.showWaitCreateTableLayer(gameName);

                //加入房间
                that.sendJoinRoom(gameName, roomNum);
                that.joinTableInfo = null;
            }
        }else if (type == "2"){
            //播放录像
            var replayId = that.joinTableInfo["param"];
            if (mo.sceneHelper.currentLayerName == "hall"){

                var kwxRecordOtherLayer = null;
                if (mo.mKwxRecordOtherLayer != null){
                    kwxRecordOtherLayer = mo.mKwxRecordOtherLayer;
                }else{
                    kwxRecordOtherLayer = new KwxRecordOtherLayer();
                    mo.mainLayer.addChild(kwxRecordOtherLayer);
                }
                kwxRecordOtherLayer.setReplayId(replayId);
                that.joinTableInfo = null;
            }
        }
    };

    //返回外部处理的url
    that.getExternalUrl = function(type, param, param2){
        var resultUrl = "";
        var baseUrl = mo.gameHelper.shareBaseUrl;
        if (type == 0){
            var url = "check=MjMobile&type=" + type + "&param=" + param;
            resultUrl = baseUrl + url;
        }else if (type == 1){
            var url = "check=MjMobile&type=" + type + "&param=" + param;
            resultUrl = baseUrl + url;
        }else if (type == 2){
            var url = "check=MjMobile&type=" + type + "&param=" + param;
            resultUrl = baseUrl + url;
        }
        return resultUrl;
    };

    //发送加入房间
    that.sendJoinRoom = function(gameName, roomId){
        if (gameName == "kwx"){
            if (roomId < 200000){
                mo.gameMsgManager.kwxGameModel = 1;
            }else{
                mo.gameMsgManager.kwxGameModel = 2;
            }
            mo.gameMsgManager.sendJoinFreeRequestkwxJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }else if (gameName == "nn"){
            mo.gameMsgManager.sendJoinFreeRequestnnJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }else if (gameName == "gsbdx"){
            mo.gameMsgManager.sendJoinFreeRequestgsbdxJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }else if (gameName == "psz"){
            mo.gameMsgManager.sendJoinFreeRequestpszJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }else if (gameName == "whmj"){
            mo.gameMsgManager.sendJoinFreeRequestWhmjJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }else if (gameName == "kwxpp"){
            mo.gameMsgManager.kwxGameModel = 2;
            mo.gameMsgManager.sendJoinFreeRequestkwxJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }else if (gameName == "dzpk"){
            mo.gameMsgManager.sendJoinFreeRequestdzpkJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }else if (gameName == "dtj"){
            mo.gameMsgManager.sendJoinFreeRequestdtjJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }else if (gameName == "pdk"){
            mo.gameMsgManager.sendJoinFreeRequestpdkJoin(mo.gameUserInfo.uid, parseInt(roomId), "123");
        }
    };

    that.getRoomCard = function(){
        if (that.user){
            var ids = that.user.items_id;
            var nums = that.user.items_num;
            var card = that.getItemNum(ids, nums, 20001);
            return card;
        }else{
            return 0;
        }
    };

    that.getCoupons = function(){
        if (that.user){
            var ids = that.user.items_id;
            var nums = that.user.items_num;
            var card = that.getItemNum(ids, nums, 30001);
            return card;
        }else{
            return 0;
        }
    };

    that.getItemNum = function(ids, nums, id){
        var result = 0;
        for (var i = 0; i < ids.length; i++){
            if(ids[i] == id){
                result = nums[i].low;
                break;
            }
        }
        return result;
    };

    //加载音乐
    that.loadMusicAndEffects = function(){
        var music = mo.fileHelper.getItem("musicKey");
        var effects = mo.fileHelper.getItem("effectsKey");

        that.mMusicVolume = music == undefined ? 100 : parseInt(music);
        that.mEffectsVolume = effects == undefined ? 100 : parseInt(effects);

        that.mMusicVolume = parseInt(that.mMusicVolume);
        that.mEffectsVolume = parseInt(that.mEffectsVolume);

        mo.soundHelper.setMusicVolume(that.mMusicVolume);
        mo.soundHelper.setEffectsVolume(that.mEffectsVolume);
    };

    //设置音乐和音效
    that.setMusicAndEffects = function(musicVolume, effectsVolume){
        // that.mMusicVolume = musicVolume;
        // that.mEffectsVolume = effectsVolume;
        //
        // mo.fileHelper.setItem("musicKey", that.mMusicVolume.toString());
        // mo.fileHelper.setItem("effectsKey", that.mEffectsVolume.toString());
        //
        // mo.soundHelper.setMusicVolume(that.mMusicVolume);
        // mo.soundHelper.setEffectsVolume(that.mEffectsVolume);
        //
        // mo.eventHelper.dispatch("updateMusicAndEffects");

        that.setMusicVoice(musicVolume);
        that.setEffectVoice(effectsVolume);
    };

    //设置音乐
    that.setMusicVoice = function(musicVolume){
        that.mMusicVolume = musicVolume;

        mo.fileHelper.setItem("musicKey", that.mMusicVolume.toString());

        mo.soundHelper.setMusicVolume(that.mMusicVolume);

        mo.eventHelper.dispatch("updateMusicAndEffects");
    };

    //设置音效
    that.setEffectVoice = function(effectsVolume){
        that.mEffectsVolume = effectsVolume;

        mo.fileHelper.setItem("effectsKey", that.mEffectsVolume.toString());

        mo.soundHelper.setEffectsVolume(that.mEffectsVolume);

        mo.eventHelper.dispatch("updateMusicAndEffects");
    };

    //录音关闭音乐和音效
    that.setRecordingForVolume = function(isRecording){
        if (isRecording){
            mo.soundHelper.setMusicVolume(0);
            mo.soundHelper.setEffectsVolume(0);
        }else{
            mo.soundHelper.setMusicVolume(that.mMusicVolume);
            mo.soundHelper.setEffectsVolume(that.mEffectsVolume);
        }
    };

    //加载方言
    that.loadLocalism = function(){
        that.mLocalism = mo.fileHelper.getItem("localismKey");
        if (that.mLocalism == undefined){
            that.mLocalism = 0;
        }

        if (that.mLocalism == 0){
            var localFile = "";
            if (mo.gameHelper.projectCode == 1){
                localFile = "xiangyang";
            }else{
                localFile = "guangshui";
            }
            mo.soundHelper.localSound = localFile;
        }else{
            mo.soundHelper.localSound = "mj";
        }

        //新的语音 有5种方言
        if (mo.gameHelper.projectCode == 0){
            var localFile = "";
            var localFiles = [
                "putonghua",
                "guangshui",
                "guangshui",
                "xiangyang",
                "shiyan",
                "xiaogan"
            ];
            localFile = localFiles[that.mLocalism];
            mo.soundHelper.localSound = localFile;
        }
    };

    //设置方言
    that.setLocalism = function(index){
        that.mLocalism = index;
        if (index == 0){
            var localFile = "";
            if (mo.gameHelper.projectCode == 1){
                localFile = "xiangyang";
            }else{
                localFile = "guangshui";
            }
            mo.soundHelper.localSound = localFile;
        }else{
            mo.soundHelper.localSound = "mj";
        }

        //新的语音 有5种方言
        if (mo.gameHelper.projectCode == 0){
            var localFile = "";
            var localFiles = [
                "putonghua",
                "guangshui",
                "guangshui",
                "xiangyang",
                "shiyan",
                "xiaogan"
            ];
            localFile = localFiles[index];
            mo.soundHelper.localSound = localFile;
        }

        mo.fileHelper.setItem("localismKey", that.mLocalism.toString());

        mo.eventHelper.dispatch("updateLocalism");
    };

    //设置地理位置经纬度
    that.setPhoneLocation = function(locationJson){
        var location = JSON.parse(locationJson);
        that.latitude = location[0];
        that.longitude = location[1];

        // var showMsg = "latitude:" + that.latitude + " longitude:" + that.longitude;
        // cc.log(showMsg);
        if (that.latitude == 0 && that.longitude == 0){
            that.phoneLocationCHS = "未能获取地理位置";
        }else{
            mo.httpClient.getPhoneLocationRegeocoding(that.latitude, that.longitude, function(success, name){
                if (success){
                    that.phoneLocationCHS = name;
                    // mo.showRoomMsgShow("您的位置:" + that.phoneLocationCHS);
                }else{
                    that.phoneLocationCHS = "未能获取地理位置";
                }
            });
        }
    };

    //设置用户手机信息
    that.setPhoneDeviceInfo = function(infoJosn){
        // cc.log("info:" + infoJosn);
        var info = JSON.parse(infoJosn);
        var platform = info.platform;
        var desc = info.desc;
        var systemVersion = info.systemVersion;
        var memory = info.memory;

        //设置当前需要的
        that.deviceInfoDesc = desc;
    };

    //获取自己是否打开了定位
    that.getMyIsOpenPhoneLocation = function(){
        var result = true;
        if (that.latitude == null ||
            that.latitude == 0 ||
            that.longitude == 0 ||
            that.longitude == null
        ){
            result = false;
        }
        return result;
    };

    //改变牌背
    that.setGameKwxCardIndex = function(index){
        if (index == "1" || index == "2" || index == "3"){
            mo.fileHelper.setItem("gameKwxCardIndex_key", index);
            that.mGameKwxCardIndex = index;
            mo.eventHelper.dispatch("changeKwxCardBg");
        }
    };

    //改变桌面背景
    that.setGameKwxBgIndex = function(index){
        if (index == "1" || index == "2" || index == "3" || index == "4" || index == "5" || index == "6"){
            mo.fileHelper.setItem("gameKwxBgIndex_key", index);
            that.mGameKwxBgIndex = index;
            mo.eventHelper.dispatch("changeKwxTableBg");
        }
    };

    //显示ip相同提示
    that.showIpEqualMsg = function(userInfos){
        var ipStruct = {};
        for (var i = 0; i < userInfos.length; i++){
            var userInfo = userInfos[i];
            if (userInfo.userid == that.uid){
                continue;
            }

            if (ipStruct[userInfo.Ip] == undefined){
                ipStruct[userInfo.Ip] = [];
            }
            ipStruct[userInfo.Ip].push(userInfo.nickname);
        }

        var showMsg = "";
        for(var key in ipStruct){
            if (ipStruct.hasOwnProperty(key)) {
                if (ipStruct[key].length > 1){
                    var nicks = ipStruct[key];
                    for (var i = 0; i < nicks.length; i++){
                        showMsg += "玩家[" + nicks[i] + "],";
                    }
                    showMsg += "ip相同，" + key + "\n";
                }
            }
        }

        if (showMsg != ""){
            mo.showMsgDialogText(showMsg);
        }
    };

    //返回用户信息
    that.getUserDeviceJsonInfo = function(deviceJson){
        var result = {};
        result.gps = "";
        result.gpsname = "";
        result.devicetype = 0;
        result.devicetext = "";
        result.ip = "";

        if (mo.gameHelper.getIsJson(deviceJson)){
            var json = JSON.parse(deviceJson);
            if (json.gps != undefined){
                result.gps = json.gps;
            }

            if (json.gpsname != undefined){
                result.gpsname = json.gpsname;
            }

            if (json.devicetype != undefined){
                result.devicetype = json.devicetype;
            }

            if (json.devicetext != undefined){
                result.devicetext = json.devicetext;
            }

            if (json.ip != undefined){
                result.ip = json.ip;
            }
        }

        return result;
    };

    //发送用户信息
    that.sendUserDeviceJson = function(){
        var json = {};
        json.gps = mo.gameUserInfo.phoneLocationCHS;
        json.gpsname = "none";
        json.devicetype = mo.gameHelper.getDeviceType();
        json.devicetext = mo.gameUserInfo.deviceInfoDesc;
        json.ip = mo.gameUserInfo.myClientIp == null ? "127.0.0.1" : mo.gameUserInfo.myClientIp;
        var jsonStr = JSON.stringify(json);

        mo.gameMsgManager.sendOnDeviceJsonChange(jsonStr);
    };

    //加载本地常用语数量
    that.loadUserCostomRate = function(){
        var userCustomTextRatekey = "key_userCustomTextRate";
        var userCostomFaceRatekey = "key_userCostomFaceRate";

        that.userCustomTextRate = mo.fileHelper.getItem(userCustomTextRatekey);
        that.userCostomFaceRate = mo.fileHelper.getItem(userCostomFaceRatekey);

        if (that.userCustomTextRate == undefined){
            that.userCustomTextRate = [];
            for (var i = 0; i < 13; i++){
                that.userCustomTextRate.push(0);
            }
        }else{
            that.userCustomTextRate = JSON.parse(that.userCustomTextRate);
        }

        if (that.userCostomFaceRate == undefined){
            that.userCostomFaceRate = [];
            for (var i = 0; i < 27; i++){
                that.userCostomFaceRate.push(0);
            }
        }else{
            that.userCostomFaceRate = JSON.parse(that.userCostomFaceRate);
        }

        //更新一次
        that.updateUserCostomRate();
    };

    //更新本地常用语频率
    that.updateUserCostomRate = function(){
        // cc.log("更新本地计数");

        var userCustomTextRatekey = "key_userCustomTextRate";
        var userCostomFaceRatekey = "key_userCostomFaceRate";

        var textJson = JSON.stringify(that.userCustomTextRate);
        var faceJson = JSON.stringify(that.userCostomFaceRate);

        mo.fileHelper.setItem(userCustomTextRatekey, textJson);
        mo.fileHelper.setItem(userCostomFaceRatekey, faceJson);

        //更新排序
        that.userCustomTextRateStruct = [];
        for (var i = 0; i < that.userCustomTextRate.length; i++){
            var item = {};
            item.index = i;
            item.rate = that.userCustomTextRate[i];
            that.userCustomTextRateStruct.push(item);
        }
        that.userCustomTextRateStruct.sort( function(a, b){
            return b.rate - a.rate;
        });

        that.userCostomFaceRateStruct = [];
        for (var i = 0; i < that.userCostomFaceRate.length; i++){
            var item = {};
            item.index = i;
            item.rate = that.userCostomFaceRate[i];
            that.userCostomFaceRateStruct.push(item);
        }
        that.userCostomFaceRateStruct.sort( function(a, b){
            return b.rate - a.rate;
        });

        //通知ui
        mo.eventHelper.dispatch("updateUserCostomRate");
    };

    return that;
};

mo.gameUserInfo = new GameUserInfo();